import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus, BadRequestException } from "@nestjs/common";
import { Response } from "express";
import { MyResponse } from "src/common/model";

@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
    catch(exception: any, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();

        const res = new MyResponse(HttpStatus.INTERNAL_SERVER_ERROR, null, exception.message || `${exception}`);

        if (exception instanceof HttpException) {
            let obj: any = exception.getResponse();
            obj = obj.message instanceof Array ? obj.message[0] || obj.error : obj.message || obj.error;
            res.code = exception.getStatus();
            res.message = obj || res.message;
        }

        response.status(res.code).json(res.toJson());
    }
}
